package com.heisenhub.file.domin;

import com.heisenhub.file.common.dto.FileDto;
import com.heisenhub.file.entity.OpFile;
import com.heisenhub.file.enums.FileStatusEnum;
import com.heisenhub.file.service.IOpFileService;
import com.heisnenhub.common.module.exception.RRException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author sen
 * @description
 * @date 2024/2/27 16:04
 */
@Slf4j
@Component
public class FileStorageManager  {



    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private IOpFileService opFileService;


    public List<Serializable> upload(MultipartFile[] files , FileDto fileDto) {
        List<OpFile> upload = fileStorageService.upload(files, fileDto);
        boolean b = opFileService.saveBatch(upload);
        if(!b) throw new RRException("文件保存失败");
        return  upload.stream().map(file -> file.getId()).collect(Collectors.toList());
    }


    public String fileUrl(String fileId) {
        OpFile byId = opFileService.getFileByFileId(fileId);
        return  fileStorageService.fileUrl(byId.getStoreService(),byId.getStorePath());
    }
    public String fileUrl(String bucketName, String fileName) {
        return  fileStorageService.fileUrl(bucketName,fileName);
    }

    public Boolean delete(String fileId) {
        OpFile byId = opFileService.getFileByFileId(fileId);
        byId.setStatus(FileStatusEnum.DELETE.getStatus());
        return  opFileService.updateById(byId);
    }


    public void download(@RequestParam(value = "fileId")String fileId, HttpServletResponse response) {
        OpFile byId = opFileService.getFileByFileId(fileId);
        fileStorageService.download(byId.getStoreService(),byId.getStorePath(),response);
    }
}
